package com.michale.framework.security.service.impl;

import com.michale.common.constants.CommonConstant;
import com.michale.common.constants.RedisCacheConstant;
import com.michale.common.domain.security.LoginUserDetail;
import com.michale.common.exception.ServiceException;
import com.michale.common.exception.user.CaptchaException;
import com.michale.common.exception.user.CaptchaExpireException;
import com.michale.common.exception.user.UserPasswordNotMatchException;
import com.michale.common.utils.String.StringUtils;
import com.michale.common.utils.i18n.MessageUtils;
import com.michale.common.utils.redis.RedisUtils;
import com.michale.framework.config.async.asyncFactory.AsyncTask;
import com.michale.framework.config.async.manager.AsyncManager;
import com.michale.framework.security.context.AuthenticationContext;
import com.michale.framework.security.service.LoginService;
import com.michale.system.service.CacheService;
import com.michale.system.service.ConfigService;
import com.michale.system.service.UserService;
import com.michale.system.vo.login.LoginBody;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author Michale
 * @apiNote 登录验证
 */
@Slf4j
@Service("loginService")
public class LoginServiceImpl implements LoginService {

    @Resource
    private AuthenticationManager authenticationManager;
    @Resource
    private ConfigService configService;
    @Resource
    private CacheService cacheService;
    @Resource
    private UserService userService;
    @Resource
    private RedisUtils redisUtils;
    @Resource
    private TokenServiceImpl tokenUtils;

    /**
     * 登录验证
     *
     * @param loginBody 登录用户信息
     * @return token
     */
    @Override
    public String login(LoginBody loginBody) {
        String userName = loginBody.getUserName();
        String password = loginBody.getPassword();
        String code = loginBody.getCode();
        String uuid = loginBody.getUuid();
        boolean captchaEnabled = configService.selectCaptchaEnabled();

        // 验证码开关
        if (captchaEnabled) {
            //校验验证码
            validateCaptcha(code, uuid);
        }
        Authentication authentication;
        try {
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userName, password);
            //将usernamePasswordAuthenticationToken放进线程中
            AuthenticationContext.setAuthentication(authenticationToken);
            //将封装的Authenticate交给AuthenticationManager
            authentication = authenticationManager.authenticate(authenticationToken);

        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                AsyncManager.asyncManager().start(AsyncTask.recordLoginInfo(userName, CommonConstant.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            } else {
                throw new ServiceException("校验结果", e.getMessage());
            }
        } finally {
            AuthenticationContext.removeAuthentication();
        }
        AsyncManager.asyncManager().start(AsyncTask.recordLoginInfo(userName, CommonConstant.REGISTER, MessageUtils.message("user.login.success")));
        if (redisUtils.hasKey(RedisCacheConstant.LOGIN_KEY + userName)) {
            throw new ServiceException("判断该账号是否已在其他设备登录","该账号已在其他设备登录", 402);
        }
        /*生成token*/
        LoginUserDetail loginUserDetail = (LoginUserDetail) authentication.getPrincipal();
        /*记录登录信息*/
        userService.recordLoginInfo(loginUserDetail.getUserId());
        return tokenUtils.createToken(loginUserDetail);
    }

    /**
     * 校验验证码
     *
     * @param code 验证码
     * @param uuid 唯一标识
     */
    @Override
    public void validateCaptcha(String code, String uuid) {
        String verifyKey = RedisCacheConstant.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, "");
        String captcha = redisUtils.getCacheObject(verifyKey);
        redisUtils.deleteObject(verifyKey);
        if (captcha == null) {
            //验证码失效异常类
            throw new CaptchaExpireException();
        }
        if (!code.equalsIgnoreCase(captcha)) {
            //验证码错误异常类
            throw new CaptchaException();
        }
    }

    /**
     * 强制其他设备登录的账号
     *
     * @param userName 用户名
     */
    @Override
    public void forceLogout(String userName) {
        String tokenId = redisUtils.getCacheObject(RedisCacheConstant.LOGIN_KEY + userName);
        cacheService.clearCacheKey(RedisCacheConstant.LOGIN_TOKEN_KEY + tokenId);
        cacheService.clearCacheKey(RedisCacheConstant.LOGIN_KEY + userName);
    }

}
